package com.jingli.pile.util;

import com.jingli.pile.domain.TokenResult;
import com.jingli.pile.entity.PlatformInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtGenerator {
    private static final String SECRET = "Abc12345!@#$%";
    private static final long EXPIRATION = 60 * 60 * 2; // 1 day in seconds

    public TokenResult generateToken(PlatformInfo platformInfo) {
        Map<String, Object> claims = new HashMap<>();
        String token =  Jwts.builder()
                .setClaims(claims)
                .setSubject(platformInfo.getPlatformId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPlatformID(platformInfo.getPlatformId());
        tokenResult.setSuccStat(0);
        tokenResult.setAccessToken(token);
        tokenResult.setTokenAvailableTime(EXPIRATION);
        tokenResult.setFailReason(0);
        return tokenResult;
    }
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = extractUsername(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
    public String extractUsername(String token) {
        return extractClaims(token).getSubject();
    }

    private Claims extractClaims(String token) {
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
    }

    private Date extractExpiration(String token) {
        return extractClaims(token).getExpiration();
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = extractExpiration(token);
        return expiration.before(new Date());
    }
}
